import { getUserDetailById, login, postUserInfo } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: '' || getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async postToken(state, loginForm) {
      const res = await login(loginForm)
      state.commit('setToken', res.data)
      return res
    },
    async getUserInfo(state) {
      const res = await postUserInfo()
      const res1 = await getUserDetailById(res.data.userId)
      state.commit('setUserInfo', { ...res.data, ...res1.data })
    },
    logOut(context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
    }
  },
  getters: {}
}
